
#include <BFont>
#include <BStyle>
#include <BOpenGL>
#include <BTreeWidget>
#include "member_BTreeItem.h"
#include "member_BTreeWidget.h"
#include "member_BStyle.h"
#include "member_BObject.h"

using namespace BWE;

member_BTreeItem::member_BTreeItem(BTreeItem* treeItem) : IAlignItem(treeItem)
{
	tree = 0;
	parent = 0;
	dirty = true;
	expanded = true;
	selected = false;
	visible = true;
	ia_form = Form_IconText;
	ia_align = Align_LeftCenter;
	indent = 0;
	graph = Graph_None;
	form = Form_None;
	border = 0;	
	checked = false;

}
member_BTreeItem::~member_BTreeItem()
{

}

void member_BTreeItem::attach(BTreeWidget* treeWidget)
{
	if (tree == treeWidget)
		return;
	tree = treeWidget;
	if (tree)
	{
		dirty = true;
		selected = false;
		if (widget)
			tree->addChild(widget);
		for (int i = 0; i < children.size(); i++)
		{
			BTreeItem* item = children[i];
			item_member(item)->attach(tree);
		}
	}
}
void member_BTreeItem::detach(BTreeWidget* treeWidget)
{
	if (tree != treeWidget)
		return;
	if (tree)
	{
		if (widget)
			tree->removeChild(widget);
		for (int i = 0; i < children.size(); i++)
		{
			BTreeItem* item = children[i];
			item_member(item)->detach(tree);
		}
		if (tree_member(tree)->selectedItems.contain(object))
		{
			selected = false;
			tree_member(tree)->selectedItems.remove(object);
			object_member(tree)->emit(Signal_ItemSelected, object);
		}
		tree_member(tree)->visualItems.remove(object);
		if (tree_member(tree)->hoveredItem == object)
		{
			tree_member(tree)->hoveredItem = 0;
			object_member(tree)->emit(Signal_ItemHovered, 0);
		}
	}
	tree = 0;
}

void member_BTreeItem::dirtyTree()
{
	if (tree)
	{
		tree_member(tree)->dirty = true;
		tree->fresh();
	}
	dirty = true;
}
void member_BTreeItem::raiseSignal(int signal, const BValue& value)
{
	BTreeItem* item = (BTreeItem*)object;
	while (item)
	{
		item->emit(signal, value);
		item = item_member(item)->parent;
	}
	if (tree)
	{
		object_member(tree)->emit(signal, value);
	}
}

void member_BTreeItem::dispenseUpperStyles(BTreeItem* upper)
{
	if (BTreeItem* parent = item_member(upper)->parent)
	{
		dispenseUpperStyles(parent);
	}
	if (BStyle* style = item_member(upper)->realStyle)
	{
		style_member(style)->apply(this);
	}
}
void member_BTreeItem::dispenseStyles(const BStyle* style)
{
	IAlignItem::dispenseStyles(style);
	if (parent)
	{
		dispenseUpperStyles(parent);
	}
}

void member_BTreeItem::adjustArrowRect(const BPoint& offset)
{
	arrowArea.setPos(area.x() + offset.x() + indent, area.y() + offset.y());
	if (arrowArea.valid())
	{
		arrowRect = arrowArea.align(tree_member(tree)->arrowAlign, tree_member(tree)->realArrowSize);
	}
}
